﻿namespace Services.BDS;

public class BDSData
{
    public static string baseurl = string.Empty;
    public static string ak, sk = string.Empty;
    public static string token = string.Empty;
    public static string tokenKey = "bds_token";

    #region 认证

    public static async Task GetToken()
    {
        if (RedisStaticHelper.Exists(tokenKey))
        {
            token = await RedisStaticHelper.GetAsync<string>(tokenKey);
        }
        else
        {
            string path = "/api/Admin/Authentication";
            var param = new
            {
                ak = ak,
                sk = sk
            };

            var res = await PostTokenRes<string>(path, param);
            if (res.code != 1)
            {
                throw new Exception($"BDS 认证失败, {res.code}, {res.msg}");
            }
            token = res.data;
            if (!string.IsNullOrWhiteSpace(token))
            {
                await RedisStaticHelper.SetAsync(tokenKey, token, TimeSpan.FromHours(12));
            }
        }
    }

    #endregion

    #region 场地
    /// <summary>
    /// 获取场地树
    /// </summary>
    /// <param name="enable"></param>
    /// <param name="isdelete"></param>
    /// <returns></returns>
    public static async Task<ResultModel<List<SiteTree>>> GetSiteTreeAsync(List<int> siteTypes, int enable = 1, int isdelete = 1)
    {
        string siteTypeParam = string.Empty;
        if (siteTypes != null && siteTypes.Count != 0)
        {
            siteTypeParam = $"&siteTypesStr={JsonConvert.SerializeObject(siteTypes)}";
        }
        string path = $"/api/School/GetSiteTree?enable={enable}&isdelete={isdelete}{siteTypeParam}";
        return await GetResultModelData<List<SiteTree>>(path);
    }

    /// <summary>
    /// 获取场地
    /// </summary>
    /// <param name="id">场地id</param>
    /// <returns></returns>
    public static async Task<BDS_Site> GetSiteAsync(int id)
    {
        string cacheKey = $"GetSiteAsync_{id}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<BDS_Site>(cacheKey);
        }
        string path = $"/api/School/GetSite?id={id}";
        var data = await GetData<BDS_Site>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    /// <summary>
    /// 获取父级场地名称
    /// </summary>
    /// <param name="pid"></param>
    /// <param name="bdsSiteList"></param>
    /// <returns></returns>
    public static string GetParentSiteNames(int pid, List<BDS_Site> bdsSiteList)
    {
        BDS_Site parent = bdsSiteList.FirstOrDefault(s => pid == s.id);
        if (parent == null)
        {
            return string.Empty;
        }
        else
        {
            string pname = GetParentSiteNames((int)parent.pid, bdsSiteList);
            if ((int)parent.pid == 0)
            {
                return "";
            }
            var str = "";
            if (string.IsNullOrEmpty(pname))
            {
                str = parent.name;
            }
            else
            {
                str = pname + "/" + parent.name;
            }
            if (str.StartsWith("/"))
            {
                str = str.Substring(1);
            }
            return str;
        }
    }
    /// <summary>
    /// 根据code获取场地
    /// </summary>
    /// <param name="code">场地code</param>
    /// <returns></returns>
    public static async Task<BDS_Site> GetSiteByCodeAsync(string code)
    {
        string cacheKey = $"GetSiteByCodeAsync_{code}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<BDS_Site>(cacheKey);
        }
        string path = $"/api/School/GetSiteByCode?code={code}";
        var data = await GetData<BDS_Site>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    /// <summary>
    /// 获取正在上课的场地编号列表
    /// </summary>
    /// <returns></returns>
    public static async Task<List<int>> GetInClassSiteIdsAsync(string aheadTime, string delayTime)
    {
        string path = $"/api/Course/GetInClassSiteIds?aheadTime={aheadTime}&delayTime={delayTime}";
        return await GetData<List<int>>(path);
    }
    /// <summary>
    /// 获取所有场地
    /// </summary>
    /// <param name="enable"></param>
    /// <param name="isdelete"></param>
    /// <returns></returns>
    public static async Task<List<BDS_Site>> GetSiteListAsync(int enable = 1, int isdelete = 1)
    {
        string cacheKey = $"GetSiteListAsync_enable_{enable}_isdelete_{isdelete}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<List<BDS_Site>>(cacheKey);
        }
        List<BDS_Site> list = new List<BDS_Site>();
        int pageindex = 1;
        string path = $"/api/School/GetSiteList?pageindex={pageindex}&pagesize=2000&enable={enable}&isdelete={isdelete}";
        List<BDS_Site> temp = await GetData<List<BDS_Site>>(path);
        while (temp.Count > 0)
        {
            list.AddRange(temp);
            temp.Clear();
            pageindex += 1;
            path = $"/api/School/GetSiteList?pageindex={pageindex}&pagesize=2000&enable={enable}&isdelete={isdelete}";
            temp = await GetData<List<BDS_Site>>(path);
        }
        if (list != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, list, TimeSpan.FromDays(1));
        }
        return list;
    }
    /// <summary>
    /// 获取场地类型
    /// </summary>
    /// <returns></returns>
    public static async Task<List<BDS_SiteType>> GetSiteTypeListAsync()
    {
        string cacheKey = $"GetSiteTypeListAsync";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<List<BDS_SiteType>>(cacheKey);
        }
        string path = "/api/School/GetSitetypeList?enable=1&isdelete=1";
        var data = await GetData<List<BDS_SiteType>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }
    public static async Task<BDS_SiteType> GetSiteTypeAsync(int id)
    {
        string cacheKey = $"GetSiteTypeAsync_{id}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<BDS_SiteType>(cacheKey);
        }
        string path = $"/api/School/GetSitetype?id={id}";
        var data = await GetData<BDS_SiteType>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }
    public static async Task<string> GetFullNameBySiteIdAsync(int siteid, int type = 4)
    {
        string cacheKey = $"GetParentNameByType_{siteid}_{type}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<string>(cacheKey);
        }
        string path = $"/api/School/GetParentNameByType?siteid={siteid}&type={type}";
        var data = await GetData<string>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }
    /// <summary>
    /// 通过全路径获取教室
    /// </summary>
    /// <param name="fullpath">全路径</param>
    /// <returns></returns>
    public static async Task<BDS_Site?> GetSiteByFullPathAsync(string fullpath)
    {
        try
        {
            var allSiteList = await GetSiteListAsync();
            BDS_Site? site = null;
            string[] orgs = fullpath.Split('/');
            List<string> nameList = new List<string>();
            foreach (string name in orgs)
                nameList.Add(name);
            List<BDS_Site> templist = allSiteList.Where(x => x.name == nameList[0]).ToList();
            nameList.RemoveAt(0);
            while (templist.Count > 0)
            {
                if (nameList.Count == 0)
                {
                    site = templist[0];
                    break;
                }
                else
                {
                    templist = allSiteList.Where(x => x.name == nameList[0]).ToList();
                    nameList.RemoveAt(0);
                }
            }
            return site;
        }
        catch (Exception)
        {
            throw;
        }
    }
    #endregion

    #region 设备

    /// <summary>
    /// 根据类型和场地获取设备（包含PackDeviceList）
    /// </summary>
    /// <param name="type"></param>
    /// <param name="site"></param>
    /// <param name="enable"></param>
    /// <param name="isdelete"></param>
    /// <returns></returns>
    public static async Task<List<BDS_DeviceModel>> GetDevicesByTypeSiteAsync(int type, int site, int enable = 1, int isdelete = 1)
    {
        string cacheKey = $"GetDevicesByTypeSite_type_{type}_site_{site}_enable_{enable}_isdelete_{isdelete}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<List<BDS_DeviceModel>>(cacheKey);
        }
        string path = $"/api/Device/GetDevicesByTypeSite?type={type}&site={site}&enable={enable}&isdelete={isdelete}";
        var data = await GetData<List<BDS_DeviceModel>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    public static async Task<BDS_DeviceModel?> GetDeviceInfoBySiteIdAsync(int siteId)
    {
        var recorderList = await GetDevicesByTypeSiteAsync(16, siteId);
        if (recorderList == null || recorderList.Count == 0)
        {
            return null;
        }
        return recorderList.First();
    }
    /// <summary>
    /// 根据id 列表查询设备
    /// </summary>
    /// <param name="deviceIds"></param>
    /// <returns></returns>
    public static async Task<List<BDS_DeviceModel>> GetDevicesByIdListAsync(List<int> deviceIds)
    {
        string path = "/api/Device/GetDevicesByIdList";
        var param = new
        {
            ids = deviceIds
        };
        return await PostData<List<BDS_DeviceModel>>(path, param);
    }

    /// <summary>
    /// 根据类型和场地获取设备
    /// </summary>
    /// <param name="type"></param>
    /// <param name="site"></param>
    /// <param name="enable"></param>
    /// <param name="isdelete"></param>
    /// <returns></returns>
    public static async Task<List<BDS_DeviceModel>> GetDevicesByTypesAndSitesAsync(List<int> deviceTypes, List<int> siteIds, int enable = 1, int isdelete = 1)
    {
        string path = "/api/Device/GetDevicesByTypesAndSites";
        var param = new
        {
            deviceTypes = deviceTypes,
            siteIds = siteIds,
            isDelete = isdelete,
            enable = enable
        };
        return await PostData<List<BDS_DeviceModel>>(path, param);
    }
    /// <summary>
    /// 根据类型和场地获取设备（包含PackDeviceList）
    /// </summary>
    /// <param name="deviceTypes"></param>
    /// <param name="siteIds"></param>
    /// <param name="enable"></param>
    /// <param name="isdelete"></param>
    /// <returns></returns>
    public static async Task<List<BDS_DeviceModel>> GetDevicesByTypeSiteAsync(List<int> deviceTypes, List<int> siteIds, int enable = 1, int isdelete = 1)
    {
        string path = "/api/Device/GetDevicesByTypeSite";
        var param = new
        {
            deviceTypes = deviceTypes,
            siteIds = siteIds,
            isDelete = isdelete,
            enable = enable
        };
        return await PostData<List<BDS_DeviceModel>>(path, param);
    }
    /// <summary>
    /// 根据场地获取设备（包含PackDeviceList）
    /// </summary>
    /// <param name="site">场地 id 必填</param>
    /// <param name="enable">是否启用 1 启用 2 禁用</param>
    /// <param name="isdelete">是否删除 1 有效 2 删除</param>
    /// <returns></returns>
    public static async Task<List<BDS_DeviceModel>> GetDevicesBySingleSiteAsync(int site, int enable = 1, int isdelete = 1)
    {
        string cacheKey = $"GetDevicesBySingleSite_site_{site}_enable_{enable}_isdelete_{isdelete}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<List<BDS_DeviceModel>>(cacheKey);
        }
        string path = $"/api/Device/GetDevicesBySingleSite?site={site}&enable={enable}&isdelete={isdelete}";
        var data = await GetData<List<BDS_DeviceModel>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    /// <summary>
    /// 获取设备(包含PackDeviceList)
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public static async Task<BDS_DeviceModel> GetDevicesAsync(int id)
    {
        string cacheKey = $"GetDevices_{id}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<BDS_DeviceModel>(cacheKey);
        }
        string path = $"/api/Device/GetDevices?id={id}";
        var data = await GetData<BDS_DeviceModel>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    /// <summary>
    /// 根据Id列表获取设备及其他信息(包含PackDeviceList)
    /// </summary>
    /// <param name="deviceIds"></param>
    /// <returns></returns>
    public static async Task<List<BDS_DeviceModel>> GetDevicesInfoByIdListAsync(List<int> deviceIds)
    {
        string path = "/api/Device/GetDevicesInfoByIdList";
        var param = new
        {
            ids = deviceIds
        };
        return await PostData<List<BDS_DeviceModel>>(path, param);
    }
    /// <summary>
    /// 根据类型获取设备(包含PackDeviceList)
    /// </summary>
    /// <param name="type"></param>
    /// <param name="enable"></param>
    /// <param name="isdelete"></param>
    /// <returns></returns>
    public static async Task<List<BDS_DeviceModel>> GetDevicesByTypeAsync(int type, int enable = 1, int isdelete = 1)
    {
        string cacheKey = $"GetDevicesByType_type_{type}_enable_{enable}_isdelete_{isdelete}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<List<BDS_DeviceModel>>(cacheKey);
        }
        string path = $"/api/Device/GetDevicesByType?type={type}&enable={enable}&isdelete={isdelete}";
        var data = await GetData<List<BDS_DeviceModel>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    
    /// <summary>
    /// 从内向外修剪树。
    /// </summary>
    /// <param name="node">当前节点。</param>
    private static bool PruneTreeFromInnerToOuter(BDS_Tree node, int current_nodetype)
    {
        if (node == null || (node.nodetype != current_nodetype && node.nodes == null)) return false;

        if (node.nodetype != current_nodetype)
        {
            int index = 0;
            while (index < node.nodes.Count)
            {
                if (!PruneTreeFromInnerToOuter(node.nodes[index], current_nodetype))
                {
                    node.nodes.RemoveAt(index); // 移除不满足条件的子节点
                }
                else
                {
                    index++;
                }
            }
        }

        // 如果是专业节点且没有子节点，则返回false表示应该移除
        if (node.nodetype != current_nodetype && (node.nodes == null || node.nodes.Count == 0))
        {
            return false;
        }

        // 其他情况下保留该节点
        return true;
    }
    public static void RemoveNodeType(List<BDS_Tree> tree, int current_nodetype)
    {
        // 本地函数，用于递归删除
        void RemoveRecursively(List<BDS_Tree> nodeList)
        {
            for (int i = nodeList.Count - 1; i >= 0; i--)
            {
                if (nodeList[i].nodetype == current_nodetype)
                {
                    nodeList.RemoveAt(i);
                }
                else
                {
                    RemoveRecursively(nodeList[i].nodes);

                    // 如果删除子节点后，当前节点变为空节点（没有子节点），可以选择是否也删除它
                    // 这里我们不实现这个逻辑，但你可以根据需要添加
                    // if (nodeList[i].nodes.Count == 0)
                    // {
                    //     nodeList.RemoveAt(i);
                    // }
                }
            }
        }

        RemoveRecursively(tree);
    }
    /// <summary>
    /// 获取设备类型
    /// </summary>
    public static async Task<List<BDS_Devicetype>> GetDevicetypeListAsync()
    {
        string cacheKey = $"GetDevicetypeList";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<List<BDS_Devicetype>>(cacheKey);
        }
        string path = "/api/Device/GetDevicetypeList";
        var data = await GetData<List<BDS_Devicetype>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }


    #endregion

    #region 公共树结构数据

    /// <summary>
    /// 获取班级树
    /// </summary>
    /// <returns></returns>
    public static async Task<BDS_Tree> GetStudentClassTreeAsync()
    {
        string cacheKey = $"GetStudentClassTreeAsync";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<BDS_Tree>(cacheKey);
        }
        string path = "/api/User/GetStudentclassTree?type=0&enable=1&isdelete=1";
        List<BDS_Tree> data = await GetData<List<BDS_Tree>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data.FirstOrDefault(), TimeSpan.FromDays(1));
        }
        return data.FirstOrDefault();
    }

    /// <summary>
    /// 获取组织树
    /// </summary>
    /// <returns></returns>
    public static async Task<BDS_Tree> GetOrgTreeAsync()
    {
        string cacheKey = $"GetOrgTreeAsync";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<BDS_Tree>(cacheKey);
        }
        string path = "/api/School/GetOrganizationTree?type=0&enable=1&isdelete=1";
        List<BDS_Tree> data = await GetData<List<BDS_Tree>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data.FirstOrDefault(), TimeSpan.FromDays(1));
        }
        return data.FirstOrDefault();
    }
    /// <summary>
    /// 获取教职工树
    /// </summary>
    /// <param name="enable"></param>
    /// <param name="isdelete"></param>
    /// <returns></returns>
    public static async Task<ResultModel<List<TeacherTree>>> GetTeacherTreeAsync(int enable = 1, int isdelete = 1)
    {
        string cacheKey = $"GetTeacherTree_enable_{enable}_isdelete_{isdelete}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<ResultModel<List<TeacherTree>>>(cacheKey);
        }
        string path = $"/api/User/GetTeacherTree?enable={enable}&isdelete={isdelete}";
        var data = await GetResultModelData<List<TeacherTree>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    /// <summary>
    /// 获取学校组织架构树
    /// </summary>
    public static async Task<ResultModel<List<OrganizationTree>>> GetOrganizationTreeAsync(int type = 0, int enable = 1, int isdelete = 1)
    {
        string cacheKey = $"GetOrganizationTree_type_{type}_enable_{enable}_isdelete_{isdelete}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<ResultModel<List<OrganizationTree>>>(cacheKey);
        }
        string path = $"/api/School/GetOrganizationTree?type={type}&enable={enable}&isdelete={isdelete}";
        var data = await GetResultModelData<List<OrganizationTree>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }

    /// <summary>
    /// 根据组织id获取老师
    /// </summary>
    /// <param name="orgId"></param>
    /// <returns></returns>
    public static async Task<ResultModel<List<BDS_Teacher>>> GetTeacherOrgAsync(int orgId)
    {
        string cacheKey = $"GetTeacherOrg_orgId_{orgId}";
        if (await RedisStaticHelper.ExistsAsync(cacheKey))
        {
            return await RedisStaticHelper.GetDecompressedValueAsync<ResultModel<List<BDS_Teacher>>>(cacheKey);
        }
        string path = $"/api/User/GetTeacherByOrgList?org={orgId}&enable=1&isdelete=1&pageindex=1&pagesize=9999";
        var data = await GetResultModelData<List<BDS_Teacher>>(path);
        if (data != null)
        {
            await RedisStaticHelper.SetCompressedValueAsync(cacheKey, data, TimeSpan.FromDays(1));
        }
        return data;
    }
    #endregion

    /// <summary>
    /// 获取返回模型包装的数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static async Task<ResultModel<T>?> GetResultModelData<T>(string path)
    {
        var bdsRes = await GetRes<T>(path);
        var resultModel = new ResultModel<T>
        {
            code = 1,
            data = bdsRes.data,
            count = bdsRes.count,
            msg = bdsRes.msg
        };
        return resultModel;
    }

    /// <summary>
    /// 获取返回模型包装的数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static async Task<ResultModel<T>?> PostResultModelData<T>(string path, object param)
    {
        BDS_Result<T>? bdsRes = await PostRes<T>(path, param);
        ResultModel<T> resultModel = new ResultModel<T>
        {
            code = bdsRes.code,
            data = bdsRes.data,
            count = bdsRes.count,
            msg = bdsRes.msg
        };
        return resultModel;
    }
    /// <summary>
    /// 查询获取数据中心
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static async Task<T> GetData<T>(string path)
    {
        BDS_Result<T>? res = await GetRes<T>(path);
        if (res == null)
        {
            throw new Exception($"获取数据中心数据错误：path: {path}");
        }
        if (res.code != 1)
        {
            throw new Exception($"获取数据中心数据错误：path: {path}, resCode: {res.code}, resMsg: {res.msg}");
        }
        return res.data;
    }

    /// <summary>
    /// 查询获取数据中心
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static async Task<BDS_Result<T>?> GetRes<T>(string path)
    {
        try
        {
            await GetToken();
            BDS_Result<T>? result = await HTTPHelper.Get<BDS_Result<T>>($"{baseurl}{path}", token);
            return result;
        }
        catch (Exception ex)
        {
            // token 过期重试
            if (ex.Message.Contains("401"))
            {
                await GetToken();
                BDS_Result<T>? result = await HTTPHelper.Get<BDS_Result<T>>($"{baseurl}{path}", token);
                return result;
            }
            if (ex.Message.Contains("无法连接"))
            {
                throw new Exception("BDS服务连接失败，请联系管理员检查服务状态");
            }
            else
            {
                throw;
            }
        }
    }

    /// <summary>
    /// 查询获取数据中心
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="param"></param>
    /// <returns></returns>
    public static async Task<T> PostData<T>(string path, object param)
    {
        BDS_Result<T>? res = await PostRes<T>(path, param);
        if (res == null)
        {
            throw new Exception($"获取数据中心数据错误：path: {path}");
        }
        if (res.code != 1)
        {
            throw new Exception($"获取数据中心数据错误：path: {path}, resCode: {res.code}, resMsg: {res.msg}");
        }
        return res.data;
    }

    /// <summary>
    /// 查询获取数据中心
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static async Task<BDS_Result<T>?> PostRes<T>(string path, object param)
    {
        try
        {
            await GetToken();
            BDS_Result<T>? result = await HTTPHelper.Post<BDS_Result<T>>($"{baseurl}{path}", param, token);
            return result;
        }
        catch (Exception ex)
        {
            // token 过期重试
            if (ex.Message.Contains("401"))
            {
                await GetToken();
                BDS_Result<T>? result = await HTTPHelper.Post<BDS_Result<T>>($"{baseurl}{path}", param, token);
                return result;
            }
            if (ex.Message.Contains("无法连接"))
            {
                throw new Exception("BDS服务连接失败，请联系管理员检查服务状态");
            }
            else
            {
                throw;
            }
        }
    }

    /// <summary>
    /// 查询获取token数据中心
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static async Task<BDS_Result<T>> PostTokenRes<T>(string path, object param)
    {
        try
        {
            var result = await HTTPHelper.Post<BDS_Result<T>>($"{baseurl}{path}", param, token) ?? new BDS_Result<T>();
            return result;
        }
        catch (Exception ex)
        {
            // token 过期重试
            if (ex.Message.Contains("401"))
            {
                await GetToken();
                var result = await HTTPHelper.Post<BDS_Result<T>>($"{baseurl}{path}", param, token) ?? new BDS_Result<T>();
                return result;
            }
            if (ex.Message.Contains("无法连接"))
            {
                throw new Exception("BDS服务连接失败，请联系管理员检查服务状态");
            }
            else
            {
                throw;
            }
        }
    }
}
